<template>
  <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" style="width: 910px;">
    <el-form :inline="true" :model="addPadMessageForm" ref="addPadMessageRef" :rules="addPadMessagerules">
      <el-form-item label="接收设备" :label-width="formLabelWidth" prop="msgId" v-if="addPadMessageForm.msgType == 5">
        <el-select clearable v-model="addPadMessageForm.msgId" autocomplete="off" placeholder="请选择接收设备"
          style="width: 180px;">
          <el-option v-for="item in roomList" :key="item.id" :value="item.name" :label="item.detail"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="接收级部" :label-width="formLabelWidth" prop="departmentId"
        v-if="addPadMessageForm.msgType == 3">
        <el-select clearable v-model="addPadMessageForm.departmentId" autocomplete="off" placeholder="请选择所在级部"
          style="width: 180px;">
          <el-option v-for="item in departmentList" :key="item.id" :value="item.id" :label="item.name"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="接收年级" :label-width="formLabelWidth" prop="gradeId"
        v-if="addPadMessageForm.msgType == 2 || addPadMessageForm.msgType == 4">
        <el-select clearable v-model="addPadMessageForm.gradeId" autocomplete="off" @change="filterGradeId"
          placeholder="请选择所在年级" style="width: 180px;">
          <el-option v-for="gradeId in gradeIds" :key="gradeId" :value="gradeId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="接收班级" :label-width="formLabelWidth" prop="classId" v-if="addPadMessageForm.msgType == 2">
        <el-select v-model="addPadMessageForm.classId" autocomplete="off" filterable placeholder="请选择班级"
          style="width: 180px;">
          <el-option v-for="item in list" :key="item.name" :label="item.name" :value="item.classId"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="展示页面" :label-width="formLabelWidth" prop="pushPage">
        <el-select v-model="addPadMessageForm.pushPage" @change="filterPushPage" style="width: 180px;">
          <el-option :value="1" label="班牌首页">班牌首页</el-option>
          <el-option :value="2" label="紧急通知页">紧急通知页</el-option>
          <el-option :value="3" label="设置页面">设置页面</el-option>
          <el-option :value="4" label="显示状态栏">显示状态栏</el-option>
          <el-option :value="5" label="隐藏状态栏">隐藏状态栏</el-option>
          <el-option :value="6" label="版本升级">版本升级</el-option>
          <el-option :value="7" label="重启设备">重启设备</el-option>
          <el-option :value="8" label="设备截屏">设备截屏</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="展示区域" :label-width="formLabelWidth" prop="msgMode" v-if="addPadMessageForm.pushPage == 1">
        <el-select v-model="addPadMessageForm.msgMode" style="width: 180px;">
          <el-option :value="2" label="图文展示区域">图文展示区域</el-option>
          <el-option :value="1" label="通知展示区">通知展示区</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="操作类型" :label-width="formLabelWidth" prop="operationType">
        <el-select v-model="addPadMessageForm.operationType" style="width: 180px;">
          <el-option :value="2" label="追加">追加</el-option>
          <el-option :value="1" label="新建">新建</el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="显示天数" :label-width="formLabelWidth" prop="days">
        <el-input-number v-model="addPadMessageForm.days" :min="1" :max="30" @change="handleChange"
          style="width: 180px;" />
      </el-form-item>
    </el-form>
    <el-form>
      <el-form-item label="消息图片" :label-width="formLabelWidth"
        v-if="addPadMessageForm.pushPage == 1 && addPadMessageForm.msgMode == 2">
        <el-upload ref="upload" :limit="6" :on-exceed="handleExceed" :auto-upload="false" multiple
          list-type="picture-card" :file-list="fileList" :on-change="fileChange" :before-remove="handleRemove"
          accept="image/jpeg,image/jpg,image/png">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="消息内容" :label-width="formLabelWidth" prop="content"
        v-if="addPadMessageForm.pushPage == 1 || addPadMessageForm.pushPage == 2">
        <el-input v-model="addPadMessageForm.content" autocomplete="off" ref="name" type="textarea" rows="6"
          placeholder="请填写消息内容"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="save()" v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm } from "element-plus";
import { vxRule } from "@/utils/validator";
import { Plus } from "@element-plus/icons-vue";

export default {
  name: "AddPadMessage",
  components: { ElForm, ElMessage, Plus },
  data() {
    return {
      dialogFormVisible: ref(false),
      formLabelWidth: "80px",
      title: "",
      fileList: [],
      personnelType: "",
      fullscreenLoading: false,
      gradeIds: [],
      list: [],
      classInfos: [],
      departmentList: [],
      roomList: [],
      map: {},
      files: [],
      files1: [],
      addPadMessageForm: {
        classId: "",
        gradeId: "",
        departmentId: '',
        classroomId: "",
        msgLevel: 0,
        msgType: "",
        days: 7,
        msgMode: 2,
        pushPage: 1,
        operationType: 2,
        padNumber: "",
        imageUrls: "",
        videoUrl: "",
        content: "",
        showStartTime: "",
        showEndTime: "",
        createTime: "",
        createName: "",
        createNameNumber: "",
        isDelete: "",
        campus: "",
        msgId: "",
      },
      // 校验规则
      addPadMessagerules: {
        classId: vxRule(true, null, "blur"),
        gradeId: vxRule(true, null, "blur"),
        pushPage: vxRule(true, null, "blur"),
        msgMode: vxRule(true, null, "blur"),
        operationType: vxRule(true, null, "blur"),
        days: vxRule(true, null, "blur"),
        departmentId: vxRule(true, null, "blur"),
        msgId: vxRule(true, null, "blur"),
      },
    };
  },
  methods: {
    filterPushPage(val) {

    },
    closeDialog() {
      this.clear();
    },

    fileChange(file, fileList) {
      this.fileList = fileList;
      if (this.files.length >= 9) {
        Snackbar.warning("只能上传9张图片");
      } else {
        const uploadedFiles = this.fileList

        for (let i = 0; i < uploadedFiles.length; i++) {
          const file = uploadedFiles[i].raw;
          let fileSize = file.size > 1024 * 3
          const reader = new FileReader();
          reader.onload = (e) => {
            const img = new Image();
            const img1 = new Image();
            const timeData = new Date().getTime();
            let myNumber = Math.floor(Math.random() * 900000) + 100000
            img.src = e.target.result;
            img.onload = () => {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              let compressedImage = ''
              const maxWidth = 1000; // 设置最大宽度
              const maxHeight = 800; // 设置最大高度
              let width = img.width;
              let height = img.height;
              if (width > height) {
                if (width > maxWidth) {
                  height *= maxWidth / width;
                  width = maxWidth;
                }
              } else {
                if (height > maxHeight) {
                  width *= maxHeight / height;
                  height = maxHeight;
                }
              }
              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, 0, 0, width, height);
              canvas.toBlob((blob) => {

                const fileimg = new File([blob], `${timeData}${myNumber}.jpg`, { type: 'image/jpeg' })
                this.files.push({ 'dataUrl': img.src, 'file': fileimg })
              }, 'image/jpeg', 0.8); // 0.8 是压缩质量，可根据需要调整
            };


            img1.src = e.target.result;
            img1.onload = () => {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              let compressedImage = ''
              const maxWidth = 500; // 设置最大宽度
              const maxHeight = 400; // 设置最大高度

              let width = img1.width;
              let height = img1.height;
              if (width > height) {
                if (width > maxWidth) {
                  height *= maxWidth / width;
                  width = maxWidth;
                }
              } else {
                if (height > maxHeight) {
                  width *= maxHeight / height;
                  height = maxHeight;
                }
              }
              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img1, 0, 0, width, height);
              let imgSize = 0.7
              if (fileSize == false) {
                imgSize = 0.9
              }
              canvas.toBlob((blob) => {
                const fileimg1 = new File([blob], `${timeData}${myNumber}.png`, { type: 'image/png' })
                this.files1.push({ 'dataUrl': img1.src, 'file': fileimg1 })
              }, 'image/jpeg', imgSize); // 0.8 是压缩质量，可根据需要调整
            };
          };
          reader.readAsDataURL(file);

        }
      }

    },
    handleRemove(value, files) {
      console.log(999, value, files);
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.files = []
      this.files1 = []
      // console.log(123,this.files, this.files1);
    },
    handleExceed(files) {
      this.$refs.upload.clearFiles();
      this.fileList = [];
      this.$refs.upload.handleStart(files[0]);
    },
    getBaseClassInfoList() {
      httpService("/javaApi/baseClassInfo/getAllEffectClass", {}, "get").then(
        (data) => {
          this.map = data;
        }
      );
    },
    getBaseDepartmentList() {
      httpService("/javaApi/baseDepartment/list/1/1000", { "type": 2 }, "get").then(
        (data) => {
          this.departmentList = data.list;
        }
      );
    },
    getNRoomList() {
      httpService(
        "/javaApi/nRoom/list/1/1000",
        {
          type: 2,
        },
        "get"
      ).then((data) => {
        this.roomList = data.list;
      });
    },
    getGradeIds() {
      let date = new Date();
      let nowYear = parseInt(date.getFullYear());
      let nowMonth = parseInt(date.getMonth());
      let gradeIds = [];
      if (nowMonth > 6) {
        gradeIds.push(nowYear - 2);
        gradeIds.push(nowYear - 1);
        gradeIds.push(nowYear);
      } else {
        gradeIds.push(nowYear - 3);
        gradeIds.push(nowYear - 2);
        gradeIds.push(nowYear - 1);
      }
      this.gradeIds = gradeIds;
    },
    filterGradeId(val) {
      this.list = this.map[val];
      this.addPadMessageForm.classId = "";
    },
    cancel() {
      this.dialogFormVisible = false;
      this.clear();
    },
    getPadMessageById(id) {
      httpService("/api/padMessage/queryById", { id: id }, "get").then(
        (data) => {
          this.addPadMessageForm = data;
        }
      );
    },
    clear() {
      this.dialogFormVisible = false;
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.fileList = [];
      //清空form
      this.addPadMessageForm.id = "";
      this.addPadMessageForm.departmentId = "";
      this.addPadMessageForm.classId = "";
      this.addPadMessageForm.gradeId = "";
      this.addPadMessageForm.classroomId = "";
      this.addPadMessageForm.msgLevel = 0;
      this.addPadMessageForm.msgType = "";
      this.addPadMessageForm.msgMode = 2;
      this.addPadMessageForm.pushPage = 1;
      this.addPadMessageForm.operationType = 2;
      this.addPadMessageForm.padNumber = "";
      this.addPadMessageForm.imageUrls = "";
      this.addPadMessageForm.videoUrl = "";
      this.addPadMessageForm.content = "";
      this.addPadMessageForm.showStartTime = "";
      this.addPadMessageForm.showEndTime = "";
      this.addPadMessageForm.createTime = "";
      this.addPadMessageForm.createName = "";
      this.addPadMessageForm.createNameNumber = "";
      this.addPadMessageForm.isDelete = "";
      this.addPadMessageForm.campus = "";
      this.addPadMessageForm.msgId = "";
      this.addPadMessageForm.days = 7;
    },

    handleFileUpload(event) {
      if (this.files.length >= 9) {
        Snackbar.warning("只能上传9张图片");
      } else {

        const uploadedFiles = event.target.files;

        for (let i = 0; i < uploadedFiles.length; i++) {
          const file = uploadedFiles[i];
          let fileSize = file.size > 1024 * 3
          const reader = new FileReader();
          reader.onload = (e) => {
            const img = new Image();
            const img1 = new Image();
            const timeData = new Date().getTime();
            let myNumber = Math.floor(Math.random() * 900000) + 100000

            img.src = e.target.result;
            img.onload = () => {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              let compressedImage = ''
              const maxWidth = 1000; // 设置最大宽度
              const maxHeight = 800; // 设置最大高度
              let width = img.width;
              let height = img.height;
              if (width > height) {
                if (width > maxWidth) {
                  height *= maxWidth / width;
                  width = maxWidth;
                }
              } else {
                if (height > maxHeight) {
                  width *= maxHeight / height;
                  height = maxHeight;
                }
              }
              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, 0, 0, width, height);
              canvas.toBlob((blob) => {

                const fileimg = new File([blob], `${timeData}${myNumber}.jpg`, { type: 'image/jpeg' })
                this.files.push({ 'dataUrl': img.src, 'file': fileimg })
              }, 'image/jpeg', 0.8); // 0.8 是压缩质量，可根据需要调整
            };




            img1.src = e.target.result;
            img1.onload = () => {
              const canvas = document.createElement('canvas');
              const ctx = canvas.getContext('2d');
              let compressedImage = ''
              const maxWidth = 500; // 设置最大宽度
              const maxHeight = 400; // 设置最大高度

              let width = img1.width;
              let height = img1.height;
              if (width > height) {
                if (width > maxWidth) {
                  height *= maxWidth / width;
                  width = maxWidth;
                }
              } else {
                if (height > maxHeight) {
                  width *= maxHeight / height;
                  height = maxHeight;
                }
              }
              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img1, 0, 0, width, height);
              let imgSize = 0.7
              if (fileSize == false) {
                imgSize = 0.9
              }
              canvas.toBlob((blob) => {
                const fileimg1 = new File([blob], `${timeData}${myNumber}.png`, { type: 'image/png' })
                this.files1.push({ 'dataUrl': img1.src, 'file': fileimg1 })
              }, 'image/jpeg', imgSize); // 0.8 是压缩质量，可根据需要调整
            };
          };
          reader.readAsDataURL(file);

        }
      }

    },

    save() {
      this.$refs.addPadMessageRef.validate((valid) => {
        if (valid) {
          console.log(this.addPadMessageForm.msgType)
          let urlPath = "add"
          if (this.addPadMessageForm.msgType == 3) {
            urlPath = 'addDepartment'
          } else if (this.addPadMessageForm.msgType == 4) {
            urlPath = 'addGrade'
          } else if (this.addPadMessageForm.msgType == 1) {
            urlPath = 'addAll'
          }

          console.log(this.addPadMessageForm.imageUrls);
          let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据

          this.dialogFormVisible = true;

          this.fullscreenLoading = true;
          params.append("classId", this.addPadMessageForm.classId);
          params.append("gradeId", this.addPadMessageForm.gradeId);
          params.append("classroomId", this.addPadMessageForm.classroomId);
          params.append("msgLevel", this.addPadMessageForm.msgLevel);
          params.append("msgType", this.addPadMessageForm.msgType);
          // params.append("msgType", 2);
          params.append("msgMode", this.addPadMessageForm.msgMode);
          params.append("pushPage", this.addPadMessageForm.pushPage);
          params.append("operationType", this.addPadMessageForm.operationType);
          params.append("padNumber", this.addPadMessageForm.padNumber);
          params.append("imageUrls", this.addPadMessageForm.imageUrls);
          params.append("videoUrl", this.addPadMessageForm.videoUrl);
          params.append("content", this.addPadMessageForm.content);
          params.append("showStartTime", this.addPadMessageForm.showStartTime);
          params.append("showEndTime", this.addPadMessageForm.showEndTime);
          params.append("msgId", this.addPadMessageForm.msgId);
          params.append("days", this.addPadMessageForm.days);
          params.append("departmentId", this.addPadMessageForm.departmentId);
          let files = new Array();

          for (let i = 0; i < this.files.length; i++) {
            params.append("file", this.files[i].file);
          }
          for (let i = 0; i < this.files1.length; i++) {
            params.append("file", this.files1[i].file);
          }

          let config = { "Content-Type": "multipart/form-data" };
          httpService(`/javaApi/padMessage/${urlPath}`, params, "post", config).then(
            (data) => {
              if (data.code == 200) {
                ElMessage.success("添加成功");
                this.clear();
                //刷新父组件的数据
                this.$parent.getPadMessageList();
              } else {
                ElMessage.error("添加失败");
              }
              this.fullscreenLoading = false;

            }
          );
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style></style>